<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>环境监控系统 - 控制中心</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        success: '#10B981',
                        danger: '#EF4444',
                        warning: '#F59E0B',
                        dark: '#1E293B',
                    },
                    fontFamily: {
                        inter: ['Inter','sans-serif'],
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
           .control-btn {
                @apply flex flex-col items-center justify-center rounded-xl transition-all duration-300 transform hover:scale-105 focus:outline-none active:scale-95;
            }

           .control-btn-icon {
                @apply text-4xl mb-2 transition-all duration-300;
            }

           .control-btn-text {
                @apply text-lg font-medium;
            }

           .status-indicator {
                @apply w-3 h-3 rounded-full inline-block;
            }

           .status-indicator.online {
                @apply bg-success animate-pulse;
            }

           .status-indicator.offline {
                @apply bg-gray-400;
            }
        }
    </style>
</head>

<body class="bg-gray-50 font-inter text-gray-800 min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <a href="/"
                class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all duration-300 flex items-center">
                <i class="fa fa-sliders mr-2"></i> 返回监控
            </a>
            <div class="flex items-center space-x-2">
                <i class="fa fa-sliders text-primary text-xl"></i>
                <h1 class="text-lg font-bold text-primary">控制中心</h1>
            </div>
            <div class="flex items-center">
                <span class="text-sm text-gray-600 mr-2">MQTT状态:</span>
                <span class="status-indicator online"></span>
                <span class="text-sm font-medium text-success ml-1" id="mqttStatus">已连接</span>
            </div>
        </div>
    </header>

    <main class="flex-1 container mx-auto px-4 py-6">
        <!-- 控制区域 -->
        <section class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <!-- 门控制卡片 -->
            <div class="bg-white rounded-xl shadow-md p-6 transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-800">门控制</h2>
                    <span class="px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-700"
                        id="doorStatus">状态: 关闭</span>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <!-- 开门按钮 -->
                    <button id="openDoor" class="control-btn bg-success/10 text-success p-6 hover:bg-success/20">
                        <i class="fa fa-door-open control-btn-icon"></i>
                        <span class="control-btn-text">开门</span>
                    </button>

                    <!-- 关门按钮 -->
                    <button id="closeDoor" class="control-btn bg-danger/10 text-danger p-6 hover:bg-danger/20">
                        <i class="fa fa-door-closed control-btn-icon"></i>
                        <span class="control-btn-text">关门</span>
                    </button>
                </div>
            </div>

            <!-- 灯光控制卡片 -->
            <div class="bg-white rounded-xl shadow-md p-6 transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-800">灯光控制</h2>
                    <span class="px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-700"
                        id="lightStatus">状态: 关闭</span>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <!-- 开灯按钮 -->
                    <button id="turnOnLight" class="control-btn bg-warning/10 text-warning p-6 hover:bg-warning/20">
                        <i class="fa fa-lightbulb control-btn-icon"></i>
                        <span class="control-btn-text">开灯</span>
                    </button>

                    <!-- 关灯按钮 -->
                    <button id="turnOffLight" class="control-btn bg-danger/10 text-danger p-6 hover:bg-danger/20">
                        <i class="fa fa-power-off control-btn-icon"></i>
                        <span class="control-btn-text">关灯</span>
                    </button>
                </div>
            </div>
        </section>

        <!-- 操作日志 -->
        <section>
            <h2 class="text-xl font-bold text-gray-800 mb-4">操作日志</h2>

            <div class="bg-white rounded-xl shadow-md p-4">
                <div class="flex justify-between items-center mb-4">
                    <div class="text-sm text-gray-500">显示最近操作</div>
                    <button id="clearLog" class="text-primary hover:text-primary/80 text-sm flex items-center">
                        <i class="fa fa-trash mr-1"></i> 清空
                    </button>
                </div>

                <div class="max-h-64 overflow-y-auto space-y-3" id="actionLog">
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <div class="flex justify-between">
                            <span class="text-sm font-medium">系统启动</span>
                            <span class="text-xs text-gray-500">10:30:45</span>
                        </div>
                        <div class="text-xs text-gray-600 mt-1">MQTT连接成功</div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-white shadow-inner py-4">
        <div class="container mx-auto px-4 text-center text-sm text-gray-500">
            <p>© 2025 环境监控系统 | 嵌入式解决方案</p>
        </div>
    </footer>

    <script>
        // 添加操作日志
        function addActionLog(action, status) {
            const now = new Date();
            const timeString = now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });

            const logContainer = document.getElementById('actionLog');
            const logItem = document.createElement('div');
            logItem.className = 'p-3 bg-gray-50 rounded-lg transition-all duration-300';

            const headerDiv = document.createElement('div');
            headerDiv.className = 'flex justify-between';

            const actionSpan = document.createElement('span');
            actionSpan.className = 'text-sm font-medium';
            actionSpan.textContent = action;

            const timeSpan = document.createElement('span');
            timeSpan.className = 'text-xs text-gray-500';
            timeSpan.textContent = timeString;

            headerDiv.appendChild(actionSpan);
            headerDiv.appendChild(timeSpan);

            const statusDiv = document.createElement('div');
            statusDiv.className = 'text-xs text-gray-600 mt-1';
            statusDiv.textContent = status;

            logItem.appendChild(headerDiv);
            logItem.appendChild(statusDiv);

            // 添加到顶部并设置动画
            if (logContainer.firstChild) {
                logContainer.insertBefore(logItem, logContainer.firstChild);
            } else {
                logContainer.appendChild(logItem);
            }

            // 限制日志数量
            if (logContainer.children.length > 5) {
                logContainer.removeChild(logContainer.lastChild);
            }
        }

        // 发送MQTT控制命令
        function sendMqttCommand(topic, payload) {
            // 显示加载状态
            addActionLog(`正在发送 ${topic} 指令...`, '处理中');

            // 构造要发送的数据
            const device = topic === 'door/control'? 'door' : 'light';
            const controlData = {
                device: device,
                action: payload
            };

            // 使用fetch调用后端API
            fetch('/api/control', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(controlData)
            })
               .then(response => response.json())
               .then(data => {
                    if (data.status ==='success') {
                        addActionLog(`发送 ${topic} 指令`, '成功');
                        // 这里可以根据后端返回的命令更新状态显示，目前后端返回的命令只是格式如"door:open"，需要进一步解析
                        if (topic === 'door/control') {
                            if (payload === 'open') {
                                document.getElementById('doorStatus').textContent = '状态: 打开';
                            } else {
                                document.getElementById('doorStatus').textContent = '状态: 关闭';
                            }
                        } else if (topic === 'light/control') {
                            if (payload === 'on') {
                                document.getElementById('lightStatus').textContent = '状态: 开启';
                            } else {
                                document.getElementById('lightStatus').textContent = '状态: 关闭';
                            }
                        }
                    } else {
                        addActionLog(`发送 ${topic} 指令`, '失败');
                    }
                })
               .catch(error => {
                    addActionLog(`发送 ${topic} 指令`, '失败');
                    console.error('发送指令失败:', error);
                });
        }

        // 初始化页面
        function initPage() {
            // 添加初始日志
            addActionLog('系统已启动', '成功');

            // 按钮点击事件
            document.getElementById('openDoor').addEventListener('click', function () {
                this.classList.add('scale-95');
                setTimeout(() => this.classList.remove('scale-95'), 200);
                sendMqttCommand('door/control', 'open');
            });

            document.getElementById('closeDoor').addEventListener('click', function () {
                this.classList.add('scale-95');
                setTimeout(() => this.classList.remove('scale-95'), 200);
                sendMqttCommand('door/control', 'close');
            });

            document.getElementById('turnOnLight').addEventListener('click', function () {
                this.classList.add('scale-95');
                setTimeout(() => this.classList.remove('scale-95'), 200);
                sendMqttCommand('light/control', 'on');
            });

            document.getElementById('turnOffLight').addEventListener('click', function () {
                this.classList.add('scale-95');
                setTimeout(() => this.classList.remove('scale-95'), 200);
                sendMqttCommand('light/control', 'off');
            });

            // 清空日志
            document.getElementById('clearLog').addEventListener('click', function () {
                document.getElementById('actionLog').innerHTML = '';
                addActionLog('日志已清空', '成功');
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>

</html>